module manager {

    export class GameManager extends egret.Sprite {

        public static readonly INIT_COMPLETE: string = "game_init_complete";

        public static readonly GAME_SIZE_CHANGED: string = "game_size_changed";

        public static readonly isProduct: boolean = true;

        private static instance: GameManager;

        public static getInstance(): GameManager {
            if (GameManager.instance == null) {
                GameManager.instance = new GameManager(Main.getInstance().stage);
            }
            return GameManager.instance;
        }

        public session_3rd: string = "";
        public openid: string = "";
        private score: number;
        private gameName: string;
        private loadUI: ui.LoadingUI;
        public adManager: AdManager;
        private gameSetting: GameSetting;
        private imgSpriteSheet: ui.GameSpriteSheet;
        private userSetting: user.UserSetting;
        private launchOptionsManager: LaunchOptionsManager;
        private userManager: UserManager;

        private uiManager: manager.UIManager;

        public statisticManager: StatisticsManager;

        private authPage: page.AuthPage;

        private constructor(stage: egret.Stage) {
            super();
            this.gameSetting = new GameSetting();
            this.launchOptionsManager = new LaunchOptionsManager();
            this.userSetting = new user.UserSetting();
            this.userManager = new UserManager();
            GameManager.instance = this;
            this.uiManager = new manager.UIManager();
            this.addChild(this.uiManager);
        }

        public getUserManager(): UserManager {
            return this.userManager;
        }

        public syncUserInfo(data: any): void {
            this.session_3rd = data.session_3rd;
            this.openid = data.host.user.wecha_id;
        }

        private gameClubButton: GameClubButton;

        public showGameClubButton(): void {
            if (!GameManager.isProduct) {
                return;
            }
            if (this.gameClubButton == null) {
                this.gameClubButton = wx.createGameClubButton({
                    icon: 'green',
                    style: {
                        left: 1,
                        top: 76,
                        width: 40,
                        height: 40
                    }
                });
            }
            this.gameClubButton.show();
        }

        public hideGameCludButton(): void {
            if (this.gameClubButton != null) {
                this.gameClubButton.hide();
            }
        }

        public getAppToken(): string {
            return this.appToken;
        }

        public init(stage: egret.Stage, appToken: string, appid: string = "", gameName: string = ""): void {
            DisplayManager.init(stage);
            SystemManager.init();
            this.statisticManager = new StatisticsManager(appToken);
            this.appId = appid;
            this.appToken = appToken;
            this.gameName = gameName;
            this.showLoading();
        }

        public static DEFAULT_SHARE_TITLE: string = "连连王者，来测测你的智商有多高";

        private initShare(): void {
            if (!GameManager.isProduct) {
                return;
            }
            egret.log("this.adManager.commonShare:", this.adManager.share);
            let title: string = this.adManager.getShareTitle();
            title = title.replace("%name", manager.GameManager.getInstance().getGameName());
            let img: string = this.adManager.getShareImg();
            let that = this;


            if (manager.GameManager.getInstance().adManager.isChecking()) {
                title = GameManager.DEFAULT_SHARE_TITLE;
                img = "";
            }

            wx.showShareMenu({
                withShareTicket: true,
                success: function (res) {

                },
                fail: function (res) {

                },
                complete: function (res) {

                },
            });

            wx.onShareAppMessage(function () {
                let query = '';
                if (that.statisticManager.host.wecha_id && that.statisticManager.host.wecha_id.length > 1) {
                    query = query ? query + "&" : "";
                    query += "from_wecha=" + that.statisticManager.host.wecha_id
                }
                if (that.appId) {
                    query = query ? query + "&" : "";
                    query += "from_appid=" + that.appId;
                }
                return {
                    title: title,
                    imageUrl: img,
                    query: query
                };
            });
        }

        public static COMMON_SHARE: number = 0;

        public commonShare(callback: any = null): void {
            GameManager.COMMON_SHARE = 1;
            let info: ShareInfo = this.adManager.getShareInfo();
            this.share(info.title, info.img, callback, "common_share=1");
        }

        public groupRankShare(): void {
            let info: ShareInfo = this.adManager.getShareInfo();
            this.share(info.title, info.img, null, "group_rank=1");
        }

        public scoreShare(callback: any = null): void {
            let adManager = manager.GameManager.getInstance().getAdManager();
            let adComponent = adManager;
            let title = this.adManager.getScoreShareTitle();
            title = title.replace("%name", manager.GameManager.getInstance().getGameName());
            title = title.replace("%score", manager.GameManager.getInstance().getScore().toString());
            let img: string = this.adManager.getShareImg();
            this.share(title, img, callback);
        }

        public groupShare(callback: any = null): void {
            let title = this.adManager.getShareTitle();
            title = title.replace("%name", manager.GameManager.getInstance().getGameName());
            let img: string = this.adManager.getShareImg();
            let that = this;
            let query = '';
            if (that.statisticManager.host.wecha_id && that.statisticManager.host.wecha_id.length > 1) {
                query = query ? query + "&" : "";
                query += "from_wecha=" + that.statisticManager.host.wecha_id
            }
            if (that.appId) {
                query = query ? query + "&" : "";
                query += "from_appid=" + that.appId;
            }
            this.share(title, img, callback);
        }

        public share(title: string, img: string, callback: any = null, query: string = ""): void {
            egret.log("分享参数:", query);

            if (manager.GameManager.getInstance().adManager.isChecking()) {
                title = "连连王者，来挑战你的智商";
                img = "";
            }

            wx.shareAppMessage({
                title: title,
                imageUrl: img,
                query: query,
                success: function (res) {
                    egret.log("分享成功:", res);
                    if (callback != null) {
                        callback(res);
                    }
                },
                fail: function () {
                    console.log("分享失败");
                },
                complete: function (res) {
                    egret.log("分享完成:", res);
                }
            });
        }

        public getStatisticManager(): manager.StatisticsManager {
            return this.statisticManager;
        }

        public getUIManager(): manager.UIManager {
            return this.uiManager;
        }

        public getUserSetting(): user.UserSetting {
            return this.userSetting;
        }

        public getGameName(): string {
            return this.gameName;
        }

        public getScore(): number {
            return this.score;
        }

        public setScore(score: number): void {
            console.log('setScore' + score)
            this.score = score;
        }

        public getImageNumberSpriteSheet(): ui.GameSpriteSheet {
            if (this.imgSpriteSheet == null) {
                this.imgSpriteSheet = new ui.GameSpriteSheet(manager.ResManager.getTexture("rthrtb_png"));
            }
            return this.imgSpriteSheet;
        }

        public getSetting(): GameSetting {
            return this.gameSetting;
        }

        public appId: string;
        private appToken: string;

        private showLoading(): void {
            this.loadUI = new ui.LoadingUI();
            this.addChild(this.loadUI);
            this.loadUI.addEventListener(ui.LoadingUI.LOAD_IMG_COMPLETE, this.onLoadUIImageLoaded, this);
            this.userManager.login(function(){
                this.loadGameConfig();
            }.bind(this));
        }

        private onLoadUIImageLoaded(): void {
            this.loadUI.removeEventListener(ui.LoadingUI.LOAD_IMG_COMPLETE, this.onLoadUIImageLoaded, this);
            // this.adManager.addEventListener(AdManager.LOAD_CONFIG_COMPLETE,
            //     this.onGameConfigLoaded, this);
            // this.adManager.loadConfig();
        }

        private onGameConfigLoaded(eve: egret.Event): void {
            this.adManager.removeEventListener(AdManager.LOAD_CONFIG_COMPLETE,
                this.onGameConfigLoaded, this);
            this.dispatchEvent(new egret.Event(GameManager.INIT_COMPLETE));
            this.initShare();
        }

        public getLoadUI(): ui.LoadingUI {
            return this.loadUI;
        }

        public hideLoadingUI(): void {
            manager.DisplayManager.remove(this.loadUI);
        }

        public getAdManager(): AdManager {
            return this.adManager;
        }

        public getLaunchOptionsManager(): LaunchOptionsManager {
            return this.launchOptionsManager;
        }

        public showAuthPage(): void {
            if (this.authPage == null) {
                this.authPage = new page.AuthPage();
            }
            this.authPage.show();
        }

        //新版初始化
        public static auditData: any;
        public agent = 0;
        public static GAME_TYPE = "game";
        private loadGameConfig() {
            let data = {
                id: StatisticsManager.commit_id,
                agent: this.getAgent()
            }
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open("https://2zhuji.cn/index.php?g=Wap&m=Wxa&a=get_audit_status", egret.HttpMethod.GET);
            request.send(data);
            request.addEventListener(egret.Event.COMPLETE, function(event){
                let request = <egret.HttpRequest>event.currentTarget;
                let data = JSON.parse(request.response);
                GameManager.auditData = data;
                if ((data["set"]["gdt_audit"] == "0") && (data["data"] != "3003")) {
                    //盒子
                    GameManager.GAME_TYPE = "box";
                    this.dispatchEvent(new egret.Event(GameManager.INIT_COMPLETE));
                } else {
                    //游戏初始化
                    this.adManager = new AdManager(this.appToken);
                    this.adManager.addEventListener(AdManager.LOAD_CONFIG_COMPLETE,
                        this.onGameConfigLoaded, this);
                    this.adManager.loadConfig();
                    this.userManager.getUserInfo(true);
                }
            }, this);
        }

        public getAgent(): number {
            if (!this.agent) {
                let sys = wx.getSystemInfoSync().system;
                sys = sys.toLowerCase();
                this.agent = (sys.indexOf("ios") == -1) ? 2 : 1;
            }
            return this.agent;
        }

        public getSession(session) {
            session = (session && (session != "0") && (session.indexOf("y1yad_") == -1)) ? "y1yad_" + session : session
            return session
        }
    }


    export class GameSetting {

        private musicEnabled: boolean = true;

        public musicToggle(): void {
            this.musicEnabled = !this.musicEnabled;
            if (this.musicEnabled) {
                wx.showToast({
                    title: '开启音效',
                    icon: 'success',
                    duration: 2000
                });
            } else {
                wx.showToast({
                    title: '关闭音效',
                    icon: 'success',
                    duration: 2000
                });
            }
        }

        public getMusicEnabled(): boolean {
            return this.musicEnabled;
        }
    }
}